package controller

import (
	"github.com/gin-gonic/gin"
	"go-shop-demo/app/common"
	"go-shop-demo/app/consts"
	"go-shop-demo/app/dto"
	"go-shop-demo/app/service"
	"log"
	"net/http"
)

//注册
func Register(c *gin.Context) {
	//获取表单用户名密码
	name := c.PostForm("name")
	password := c.PostForm("password")
	if len(name) == 0 || len(password) == 0 {
		c.JSON(401, common.NewResponse(401, "用户名或密码不存在", nil))
		return
	}
	err := service.Register(name, password)
	if err != nil {
		log.Printf("err:%v", err)
		c.JSON(401, common.NewResponse(401, err.Error(), nil))
		return
	}
	c.JSON(http.StatusOK, common.GetResponseWithMsg(nil, "注册成功"))
	return
}

func Login(c *gin.Context) {
	name := c.PostForm("name")
	password := c.PostForm("password")
	err, user := service.Login(name, password)
	common.CheckErr(err, consts.ServerError, "")
	res := dto.NewUserDetailDto(user)
	c.JSON(http.StatusOK, common.GetResponseWithMsg(res, "登录成功"))
}
